// 游戏已开始的ws请求
import { writeFileSync } from 'fs'
import {
  conn_house_data,
  house_data,
  update_house_status, 
  update_user_status,
  clear_last_data,
  random_problem,
  join_wait_add_score,
  reset_house,
  update_conn } from '~/database/socketData.js'
import { wsSend, sleep, house_every_send_conn, sort} from '~/websocket/utils.js'
import { 
  $begin_house_info, 
  $draw_countdown,
  $self_draw_problem,
  $ready_guess_problem,
  $score,
  $game_begin,
  $draw_steps,
  $game_over,
  $house_err,
  $onece_again_err,
  $other_answer,
  $draw_revoke
 } from '~/websocket/types.js'
//const house_data = {}
  // house_id:{
  // status:0,0准备1开始,2计分中，3已结束，4休息整理中
  // problem:'泪流成河'
  // problem_id:1, 做题id
  // problem_tip:'山水类的'，
  // updatedAt:'',
  // members:{
  //   openid:{
      //   conn:conn,
      //   draw_data:[],
      //   name: String,
      //   avatarUrl:String,
      //   gender:Number,
      //   m_status:Number,// 0准备1猜题，2作画
      //   wait_add_score:2,
      //   score:Number,
      
      //  },
  // }
  // 

// 作画计时,并发送到每个人设备上
export const draw_countdown =  (house_id,openid) => {
  return new Promise((resolve,reject) =>{
    let i = 120;
    let length = Object.keys(house_data[house_id].members).length;
    let score_num = 0
    const timeId = setInterval(async () => {
      if(!house_data[house_id].members[openid]){
        // 断线被剔除了就会找不到，不对任何人做计分
        i = 120;
        clearInterval(timeId)
        resolve()
        return;
      }
      for(const openid in house_data[house_id].members){
        if(house_data[house_id].members[openid]){
          if(parseInt(house_data[house_id].members[openid].wait_add_score) !== 0){
            console.log(123)
            // score_num是看有几个人已作对的人数，全做对可提前结束循环
            score_num++
          }
        }else{
          console.log(1235)
          // 掉线人员在length减1
          length --
        }
      }
      // i等于-1代表时间到，// score_num === length代表提前答对了，
      if(i === -1 || score_num === length){
        i = 120;
        clearInterval(timeId)
         // 计时结束后发送计分
        await send_score(house_id)
        // 休息10秒
        await sleep(10000)
        resolve()
        return;
      }
      
      if(house_data[house_id]){
        house_every_send_conn(house_id,{
          type: $draw_countdown,
          data:i
        })
      }
      i-- 
    },1000);
  })
}
// 每个人循环作画
export const drawing =   (house_id) => {
  return new Promise(async (resolve,reject) =>{
    for (let openid in house_data[house_id].members) {
      // 将房间状态改成开始状态
      update_house_status(house_id,1)
      // 开始随机出题
      await random_problem(house_id)
      // 清空房间内上一个作画预计得分数字。和保存的canvas等数据
      clear_last_data(house_id)

      const sendData = {
        members:house_data[house_id].members,
        current_user:house_data[house_id].members[openid].name,problemData:{
          problem: house_data[house_id].problem,
          problem_id: house_data[house_id].problem_id,
          problem_tip: house_data[house_id].problem_tip
        }
      }
      // 计时前先把每人状态改变，并通知每人下一题马上开始
      for(let user_openid in house_data[house_id].members){
        if(openid === user_openid){
          await update_user_status(house_id,user_openid,2)
          wsSend(conn_house_data[house_id].members[user_openid].conn,{
            type:$self_draw_problem,
            data:sendData
          })
        }else{
          await update_user_status(house_id,user_openid,1)
          wsSend(conn_house_data[house_id].members[user_openid].conn,{
            type:$ready_guess_problem,
            data:sendData
          })
          
        }
        
      }
      //更新房间member状态
      house_every_send_conn(house_id,{
        type:'members',
        data:house_data[house_id].members
      })
      await draw_countdown(house_id,openid);
    }
    resolve()
  })
}
// 开始作画
export const start_game =  async (house_id) => {
  // 3轮
  for(let i = 0;i<3;i++){
    // 开始作画
    await drawing(house_id)
  }
  const members = house_data[house_id].members
  const m_arr = []
  for(const openid in members){
    const obj = Object.assign({},members[openid],{draw_data:[]})
    m_arr.push(obj)
  }
  
  // 游戏结束，按照高低顺序发送名次
  house_every_send_conn(house_id,{
    type:$game_over,
    data:sort(m_arr)
  })
  // 更新房间状态为结束game
  update_house_status(house_id,3)
}

// 用户点击开始游戏，通知所有人游戏开始，跳转页面
export const click_game_begin = (conn,str) => {
  const {house_id} = str;
  if(house_id && house_data[house_id].status === 0){
    house_every_send_conn(house_id,{type: $game_begin})
    setTimeout(()=>{
      // 等三秒是为了怕网络延迟，客户端有些人还没进入页面
      start_game(house_id)
    },3000)
    
  }else{
    wsSend(conn,{
      type:$house_err,
      data:'房间已开始'
    })
  }
}
// 2秒的时间统计得分，
export const send_score = async (house_id) => {
  // 更新房间状态计分中
  update_house_status(house_id,2)
  return new Promise((resolve,reject) =>{
    setTimeout(() => {
      const members = house_data[house_id].members
      const sendData = []
      for(let key in members){
        members[key].score += members[key].wait_add_score
        sendData.push(Object.assign({},members[key],{draw_data:[]}))
      
      }
      house_every_send_conn(house_id,{
        type:$score,
        data:sendData
      })
      update_house_status(house_id,4)
      resolve()
    },2000)
  })
}
// 答对将分数放入待加区，等待游戏结束一并加入，等待结束是担心作画者中途退出，导致得分不公平
export const wait_add_score = (conn,str) => {
  // score=0代表答错
  const {is_right,house_id,openid,score,answer,name} = str;
  const data ={answer,name, is_right}
  
  if(house_id && openid && score && answer && is_right){
    if( house_data[house_id].problem == answer){
      join_wait_add_score({house_id,openid,score})
    }else{
      console.log('服务器的答案与客户端的正确答案不匹配')
    }
    
  }
  house_every_send_conn(house_id,{
    type:$other_answer,
    data:data
  })
}
// 游戏已经开始，进入作画页面时获取房间信息
export const get_begin_house_info = (conn,str) => {
  const {house_id,openid} = str;
  if(house_data[house_id]){
    // 担心是退出app后进来重新生成的conn，所以进入页面是重新保存最新的
    update_conn({conn, house_id, openid})
    // 返回游戏中的成员
    wsSend(conn,{type: $begin_house_info,data:house_data[house_id]})
  }else{
    wsSend(conn,{type:$house_err,data:'房间已过期'})
  }
  
}
// 保存当前作画人的数据，并发送给每人
export const save_draw_steps = (conn,str) => {
  const { house_id,openid,steps,color,width } = str;
  if(house_data[house_id] && house_data[house_id].members[openid]){
    const data = {steps,color,width }
    house_data[house_id].members[openid].draw_data.push(data)
    for(let key in conn_house_data[house_id].members){
      if(openid !== key){// 不给自己回传
        const s_conn = conn_house_data[house_id].members[key].conn;
        wsSend(s_conn,{
          type:$draw_steps,
          data:data
        })
      }
    }
  }
}
// 再来一次
export const onece_again = (conn,str) => {
  
  if(str.house_id){
    if(house_data[str.house_id].status !== 3){
      // 房间不处于结束状态，说明有人已经点过开始了
      return;
    }
    if(Object.keys(house_data[str.house_id].members).length > 1){
      // 重置房间状态
      reset_house(str.house_id)
      // 准备开始
      click_game_begin(conn,str)
    }else{
      wsSend(conn,{
        type:$onece_again_err,
        data:'房间人数不够2人'
      })
    }
  }else{
    wsSend(conn,{
      type:$onece_again_err,
      data:'房间没已被销毁，请重新创建'
    })
  }
}
export const draw_revoke = (conn,str) =>{
  const {house_id,openid,type} = str;
  if(house_data[house_id]){
    // type 1清除画布，2撤销
    let draw_data = house_data[house_id].members[openid].draw_data;
    if(type === 1){ // 
      draw_data = [];
    }else if(type === 2){
      draw_data.splice(draw_data.length-1,1)
    }
    house_every_send_conn(house_id,{
      type: $draw_revoke,
      data:{
        draw_data,
        type
      }
    })
  }else{
    wsSend(conn,{
      type:$onece_again_err,
      data:'没有找到房间'
    })
  }
}
